<?php
require_once(LIBPATH.'sql.php');

/*
 * Created on 12/03/2008
 *
 */
class tableGallery extends table
{

   /*** Creates the PDO Connection and the table...
    *
    */
    public function __construct()
    {
    	parent::table('photo');
        $this->addColumn('file'   , 'VARCHAR(255) NOT NULL PRIMARY KEY');
        $this->addColumn('msg'    , 'VARCHAR(255)');
        $this->db->query($this->create());
    }


    /**
    * Insert/change photo data
    *
    */
    function savePhotoData($data)
    {

        $temp = $this->getPhotoData($data['file']);
        $mode = 'ins';

        if ($temp)
        {
            foreach ($temp as $row)
            {
                if ( $row['file'])
                {
                    $mode = 'up';
                }
                else
                {
                    $mode = 'ins';
                }
            }
        }

        if ($mode == 'ins')
        {
            $sql = $this->insert($data);
        }
        else
        {
            $sql = $this->update($data);
        }

        return $this->db->exec( $sql );
    }


    /**
    * Return information about photos
    *
    */
    public function getPhotoData($file=null)
    {
        $this->clearWhere();
        if ($file)
        {
            $this->addWhere("file  ="  , $file);
        }

        $result =  $this->db->query( $this->select() );

        return $this->resultToArray($result);
    }


    public function getJsPhotoData()
    {
        if ($photoData = $this->getPhotoData())
        {
            //convert it to needed format
            foreach ($photoData as $line => $info)
            {
                $result[$info['file']] = $info['msg'];
            }
            $script     = (toJsArray($result, 'photoData'));
        }
        else
        {
            $script     = ('var photoData = new Array(0);');
        }
        return $script;
    }

    /**
    * Delete the reference to file in datadb..
    *
    */
    public function delete($folder, $file)
    {
        $this->clear();

        if ($file)
        {
        	//verificar se exit antes de excluir, pra n�o dar pau...
        	$this->addWhere("file  ="  , $file);
            $dbRemove = $this->db->query( parent::delete() );
            $fileRemove = deleteFile($folder, $file);
            if ($dbRemove && $fileRemove)
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    public function getImageDescription($file)
    {
        $this->clear();

        if ($file)
        {
            $this->addWhere("file  ="  , $file);
        }
        else
        {
        	return false;
        }

        $result =  $this->db->query( $this->select() );

        $return = $this->resultToArray($result);

        return $return[0]['msg'];

    }
}
?>